import json

from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404
from django.views.generic.base import TemplateView, View
from django.contrib.auth import get_user_model

from custom import BreadcrumbMixin

User = get_user_model()  # 所有用户信息

from .mixin import LoginRequiredMixin
from .models import Structure
from .forms import StructureForm


class StructureView(LoginRequiredMixin, BreadcrumbMixin, TemplateView):
    template_name = 'system/structure/structure.html'


class StructureCreateView(LoginRequiredMixin, View):
    """创建组织架构"""

    def get(self, request):
        ret = dict(structure_all=Structure.objects.all())
        id = request.GET.get('id', None)
        if id:
            structure = get_object_or_404(Structure, pk=id)
            ret['structure'] = structure
        return render(request, 'system/structure/structure_create.html', ret)

    def post(self, request):
        ret = dict(result=False)
        id = request.GET.get('id', None)
        if id:
            structure = get_object_or_404(Structure, pk=id)
        else:  # id 为空，则使用空的模型作为instance关键参数
            structure = Structure()
        structure_form = StructureForm(request.POST, structure)
        if structure_form.is_valid():
            structure_form.save()  # 保存到数据库
            ret['result'] = True

        return JsonResponse(ret)


class StructureListView(LoginRequiredMixin, View):
    """组织架构列表视图"""

    def get(self, request):
        fields = ['id', 'name', 'type', 'parent__name']
        ret = dict(data=list(Structure.objects.values(*fields)))
        print(ret)
        return JsonResponse(ret)


class StructureDeleteView(LoginRequiredMixin, View):
    """删除视图"""

    def post(self, request):
        ret = dict(result=False)
        id = request.POST.get('id', None)
        if id:
            id_list = map(int, request.POST['id'].split(','))
            Structure.objects.filter(id__in=id_list).delete()
            ret['result'] = True
        return JsonResponse(ret)


class Structure2UserView(LoginRequiredMixin, View):

    def get(self, request):
        ret = dict(structure=None)
        id = request.GET.get('id', None)
        if id:
            structure = get_object_or_404(Structure, pk=int(id))
            added_users = structure.userprofile_set.all()  # 所有已绑定该组织架构的用户信息
            all_users = User.objects.all()  # 所有用户信息
            # 计算差集，得出未绑定该组织的用户，将数据返回前端，左侧为未绑定的用户，右侧为已绑定的用户
            un_add_users = set(all_users).difference(added_users)
            ret = dict(structure=structure, added_users=added_users, un_add_users=list(un_add_users))

        return render(request, 'system/structure/structure_user.html', ret)

    def post(self, request):
        res = dict(result=False)
        id_list = None
        structure = get_object_or_404(Structure, pk=int(request.POST.get('id')))

        # 获取需要绑定到 structure 实例的用户 id
        to = request.POST.get('to', [])
        if to:
            id_list = map(int, to)

        # 清空组织架构原有用户绑定的信息
        structure.userprofile_set.clear()
        if id_list:
            # 绑定新的用户数据
            for user in User.objects.filter(id__in=id_list):
                structure.userprofile_set.add(user)
        res['result'] = True

        return JsonResponse(res)


class CreateUserView(LoginRequiredMixin, View):

    def get(self, request):
        from .models import UserProfile

        user = UserProfile.objects.create_user(username='马小二', password='123456')

        return render(request, 'system/structure/structure_user.html')
